package com.offcn.sellergood.service.impl;
import com.alibaba.fastjson.JSON;
import com.offcn.sellergood.dao.*;
import com.offcn.sellergood.entity.GoodsEntity;
import com.offcn.sellergood.pojo.Goods;
import com.offcn.sellergood.pojo.GoodsDesc;
import com.offcn.sellergood.pojo.Item;
import com.offcn.sellergood.service.GoodsService;

import com.offcn.entity.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/****
 * @Author:ujiuye
 * @Description:Goods业务层接口实现类
 * @Date 2021/2/1 14:19
 *****/
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper,Goods> implements GoodsService {

    @Autowired(required = false)
    private GoodsDescMapper goodsDescMapper;

    @Autowired(required = false)
    private ItemMapper itemMapper;
    @Autowired(required = false)
    private GoodsMapper goodsMapper;

    // 因为tb_goods中三级分类的ID ==> item表中的category存储第三级分类名
    @Autowired(required = false)
    private ItemCatMapper itemCatMapper;

    @Autowired(required = false)
    private BrandMapper brandMapper;

    @Override
    public void add(GoodsEntity goodsEntity) {
        //保存tbGoods表的数据
        Goods tbGoods = goodsEntity.getTbGoods();
        this.save(tbGoods);
        Long goodsId = tbGoods.getId();
        //保存tbGoodsDese 表的数据
        GoodsDesc tbGoodsDesc = goodsEntity.getTbGoodsDesc();
        tbGoodsDesc.setGoodsId(goodsId);
        goodsDescMapper.insert(tbGoodsDesc);
        // 保存item表的数据
        // 如果tbGoods.getIsEnableSpec() 为1，表示有item数据
        if("1".equals(tbGoods.getIsEnableSpec())){
            List<Item> itemList = goodsEntity.getItemList();
            if (!CollectionUtils.isEmpty(itemList)){
                for (Item item:itemList){
                    // sku的title
                    // 重新定义名字 和 规格进行挂钩
                    String title = tbGoods.getGoodsName();//getGoodsName获得goods中的名字 然后作为item表中标题的一部分
                    Map<String,String> specMap = JSON.parseObject(item.getSpec(), Map.class);
                    for (String key : specMap.keySet()) {
                        title += key + "_" +specMap.get(key) + " ";
                    }
                    item.setTitle(title);
                    // 通过 tbgoods中 category_3 的值获取 对应 categoryName
                    String categoryName = itemCatMapper.selectById(tbGoods.getCategory3Id()).getName();
                    item.setCategory(categoryName);
                    item.setCategoryId(tbGoods.getCategory3Id());
                    //状态
                    item.setStatus("0"); // 未审核状态
                    // 创建时间和修改时间
                    item.setCreateTime(new Date());
                    item.setUpdateTime(new Date());
                    // 商品Id
                    item.setGoodsId(goodsId);
                    item.setSellerId(tbGoods.getSellerId());
                    // image 获取 tbGoodsDesc 中第一张图片
                    List<Map> imageList = JSON.parseArray(tbGoodsDesc.getItemImages(), Map.class);
                    if (!CollectionUtils.isEmpty(imageList)) {
                        String url = (String)imageList.get(0).get("url");
                        item.setImage(url);
                        // 品牌
                        String brandName = brandMapper.selectById(tbGoods.getBrandId()).getName();
                        item.setBrand(brandName);
                        // 添加
                        itemMapper.insert(item);
                    }
                }
            }else{ // 没有item数据，同样需要在item中插入一条数据
                Item item = new Item();
                item.setTitle(tbGoods.getGoodsName());
                item.setPrice(new BigDecimal(tbGoods.getPrice()));
                item.setNum(9999);
                String categoryName = itemCatMapper.selectById(tbGoods.getCategory3Id()).getName();
                item.setCategory(categoryName);
                item.setCategoryId(tbGoods.getCategory3Id());
                item.setStatus("0"); // 未审核状态
                // 创建时间和修改时间
                item.setCreateTime(new Date());
                item.setUpdateTime(new Date());
                // 商品Id
                item.setGoodsId(goodsId);
                // sellerId
                item.setSellerId(tbGoods.getSellerId());
                // image 获取 tbGoodsDesc 中第一张图片
                List<Map> imageList = JSON.parseArray(tbGoodsDesc.getItemImages(), Map.class);
                if (!CollectionUtils.isEmpty(imageList)) {
                    String url = (String)imageList.get(0).get("url");
                    item.setImage(url);
                }
                // 品牌
                String brandName = brandMapper.selectById(tbGoods.getBrandId()).getName();
                item.setBrand(brandName);
                // 添加
                itemMapper.insert(item);
            }
        }


    }
    /**
     * 根据Id获取商品信息
     */

    @Override
    public GoodsEntity findById(Long id) {
        // 先获取tbGoods表的数据
        Goods tbGoods = this.getById(id);
        if (tbGoods.getIsDelete() != null && tbGoods.getIsDelete().equals("1")){
            throw new RuntimeException("当前商品已被删除");
        }
        // 再获取tbGoodsDesc表的数据
        GoodsDesc goodsDesc = goodsDescMapper.selectById(id);
        // item表的数据
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id",id);
        List<Item> items = itemMapper.selectList(queryWrapper);
        return  new GoodsEntity(tbGoods, goodsDesc, items);
    }

    @Override
    public void audit(Long goodsId) {
        Goods tbGoods = this.getById(goodsId);
        // 已经是删除状态
        if(tbGoods.getIsDelete() != null && tbGoods.getIsDelete().equals("1")){
            throw new RuntimeException("该商品已被删除");
        }
        tbGoods.setAuditStatus("1"); // 审核通过
        tbGoods.setIsMarketable("1"); // 上架状态
        this.updateById(tbGoods);
    }
    @Override
    public void pull(Long goodsId) {
        Goods tbGoods = this.getById(goodsId);
        if(tbGoods.getIsDelete() != null && tbGoods.getIsDelete().equals("1")){
            throw new RuntimeException("该商品已被删除");
        }
        tbGoods.setIsMarketable("0");  // 下架
        this.updateById(tbGoods);
    }
    @Override
    public void put(Long goodsId) {
        Goods tbGoods = this.getById(goodsId);
        if(tbGoods.getIsDelete() != null && tbGoods.getIsDelete().equals("1")){
            throw new RuntimeException("该商品已被删除");
        }
        tbGoods.setIsMarketable("1");  // 上架
        this.updateById(tbGoods);
    }
    @Override
    public int putAll(Long[] ids) {
        // update tb_goods set is_marketable = '1' where id in () and is_delete is not null;
        // 方案2
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("id",ids);
        queryWrapper.isNotNull("is_delete"); // 没有被删除
        queryWrapper.eq("auditStatus","1"); // 当前被审核通过
        Goods goods = new Goods();
        goods.setIsMarketable("1");  // 上架状态
        return goodsMapper.update(goods, queryWrapper);

    }

    @Override
    public void delete(Long id) {
        Goods tbGoods = this.getById(id);
        // 判断是否下架 ，下架之后才可以删除
        if (!tbGoods.getIsMarketable().equals("0")) {
            throw new RuntimeException("只有下架的商品才可以被删除");
        }
        // 逻辑删除
        tbGoods.setIsDelete("1");
        // 将审核状态修改为 0
        tbGoods.setAuditStatus("0");
        this.updateById(tbGoods);
    }
}
